package com.qf.controller;

import cn.dsna.util.images.ValidateCode;
import com.qf.entity.Address;
import com.qf.entity.User;
import com.qf.service.AddressService;
import com.qf.service.UserService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Base64;
import java.util.List;

/**
 * @author 10202
 * @version V1.0
 * @Project xiaomi
 * @Package ${PACKAGE_NAME}
 * @Date 2023/4/13 11:29
 */
@WebServlet(name = "UserServlet",urlPatterns = "/userservlet")
public class UserServlet extends BaseServlet {
    public String login(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");
        String auto = request.getParameter("auto");

        if(StringUtils.isEmpty(username)){
            request.setAttribute("msg","用户名不能为空");
            return "forword:/login.jsp";
        }
        if(StringUtils.isEmpty(password)){
            request.setAttribute("msg","密码不能为空");
            return "forword:/login.jsp";
        }
        if(StringUtils.isEmpty(vcode)){
            request.setAttribute("msg","验证码不能为空");
            return "forword:/login.jsp";
        }
        String code = (String) request.getSession().getAttribute("code");
        if(!vcode.equalsIgnoreCase(code)){
            request.setAttribute("msg","验证码输入不正确");
            return "forword:/login.jsp";
        }

        UserService userService=new UserServiceImpl();
        try {
            User user=userService.login(username,password);
            request.getSession().setAttribute("user",user);
            if(auto!=null){
                String userinfo=username+"#"+password;
               userinfo=Base64.getUrlEncoder().encodeToString(userinfo.getBytes("utf-8"));
                Cookie cookie=new Cookie("userinfo",userinfo);
                cookie.setPath(request.getContextPath());
                cookie.setMaxAge(60*60*24*14);
                cookie.setHttpOnly(true);
                response.addCookie(cookie);
            }
            return "forword:/index.jsp";
        } catch (Exception e) {
            request.setAttribute("msg","登录失败"+(e.getMessage().equals("用户名或者密码错误")?"用户名或者密码错误":""));
            return "forword:/login.jsp";
        }
    }
    public String register(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");

        if(StringUtils.isEmpty(username)){
            request.setAttribute("registerMsg","用户名不能为空");
            return "forword:/register.jsp";
        }
        if(StringUtils.isEmpty(password)){
            request.setAttribute("registerMsg","密码不能为空");
            return "forword:/register.jsp";
        }
        if(StringUtils.isEmpty(repassword)){
            request.setAttribute("registerMsg","确认密码不能为空");
            return "forword:/register.jsp";
        }
        if(StringUtils.isEmpty(email)){
            request.setAttribute("registerMsg","邮箱不能为空");
            return "forword:/register.jsp";
        }
        if(StringUtils.isEmpty(gender)){
            request.setAttribute("registerMsg","性别不能为空");
            return "forword:/register.jsp";
        }
        if(!password.equals(repassword)){
            request.setAttribute("registerMsg","两次密码输入不一致");
            return "forword:/register.jsp";
        }
        String reg="\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";;
        if(!email.matches(reg)){
            request.setAttribute("registerMsg","邮箱不匹配");
            return "forword:/register.jsp";
        }

        User user=new User(null,username,password,email,gender,0,1,null);

        UserService userService=new UserServiceImpl();
        try {
            userService.addUser(user);
            return "redirect:/registerSuccess.jsp";
        } catch (Exception e) {
            request.setAttribute("registerMsg","注册失败"+e.getMessage());
            return "forword:/register.jsp";
        }

    }

    public String checkUserName(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        if(StringUtils.isEmpty(username)){
            return null;
        }

        UserService userService=new UserServiceImpl();
        boolean flag=userService.queryByUsername(username);

        if(flag){
            response.getWriter().write("1");
        }else {
            response.getWriter().write("0");
        }
        return null;
    }
    public  String code(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
        ValidateCode code =new ValidateCode(130,35,4,20);
        request.getSession().setAttribute("code",code.getCode());
        code.write(response.getOutputStream());
        return null;
    }

    public String logOut(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        session.invalidate();

        Cookie cookie=new Cookie("userinfo","");
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(0);
        response.addCookie(cookie);


        return "redirect:/login.jsp";

    }
    public String getAddress(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        AddressService addressService=new AddressServiceImpl();
        try {
            List<Address> addressList = addressService.queryAddressByUid(user.getId());

            request.getSession().setAttribute("addList",addressList);
            return "self_info.jsp";
        } catch (Exception e) {
            request.setAttribute("msg","管理界面显示失败");
            return "message.jsp";
        }
    }

    public String addAddress(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
        User user = (User) request.getSession().getAttribute("user");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        if(user==null){
            return "redirect:/login.jsp";
        }
        if(StringUtils.isEmpty(name)){
            return "redirect:/index.jsp";
        }
        if(StringUtils.isEmpty(phone)){
            return "redirect:/index.jsp";
        }
        if(StringUtils.isEmpty(detail)){
            return "redirect:/index.jsp";
        }
        Address address=new Address(null,detail,name,phone,user.getId(),0);
        AddressService addressService=new AddressServiceImpl();
        try {
            addressService.addAddress(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            request.setAttribute("msg","添加地址失败");
            return "/message.jsp";
        }
    }

    public String deleteAddress(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
        String id = request.getParameter("id");
        if(StringUtils.isEmpty(id)){
            request.setAttribute("msg","删除失败");
            return "/message.jsp";
        }
        try {
            int intId = Integer.parseInt(id);
            AddressService addressServiced=new AddressServiceImpl();
            addressServiced.deleteAddressById(intId);
            return "redirect:/userservlet?method=getAddress";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg","删除地址失败");
            return "/message.jsp";
        }
    }

    public String updateAddress(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }

        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        String level = request.getParameter("level");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        if(StringUtils.isEmpty(id)){
            request.setAttribute("msg","id信息不能为空");
            return "/message.jsp";
        }
        if(StringUtils.isEmpty(level)){
            request.setAttribute("msg","默认信息不能为空");
            return "/message.jsp";
        }
        if(StringUtils.isEmpty(name)){
            request.setAttribute("msg","名字信息不能为空");
            return "/message.jsp";
        }
        if(StringUtils.isEmpty(phone)){
            request.setAttribute("msg","手机号信息不能为空");
            return "/message.jsp";
        }
        if(StringUtils.isEmpty(detail)){
            request.setAttribute("msg","地址信息不能为空");
            return "/message.jsp";
        }

        AddressService addressService=new AddressServiceImpl();
        try {
            Address address=
                    new Address(Integer.parseInt(id),detail,name,phone,user.getId(),Integer.parseInt(level));
            addressService.updateAddress(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg","删除地址失败");
            return "/message.jsp";
        }

    }

   public String defaultAddress(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
       User user = (User) request.getSession().getAttribute("user");
       if(user==null){
           return "redirect:/login.jsp";
       }
       String id = request.getParameter("id");
       if(StringUtils.isEmpty(id)){
           request.setAttribute("msg","修改默认失败");
           return "/message.jsp";
       }

       AddressService addressService=new AddressServiceImpl();
       try {
           addressService.updateAddressLevel(Integer.parseInt(id),user.getId());
           return "redirect:/userservlet?method=getAddress";
       } catch (NumberFormatException e) {
           e.printStackTrace();
           request.setAttribute("msg","修改默认失败");
           return "/message.jsp";
       }

   }
}


